/**
 * 战斗阶段管理器
 * 负责管理战斗的各个阶段处理逻辑
 */

import { 
    BattleContext, 
    BattlePhase, 
    BattlePhaseHandler,
    BattleStatus 
} from './types';
import { ServiceLogger } from '../../../infrastructure/logging/UnifiedLogger';
import { BattleStateManager } from './BattleStateManager';
import { CombatResolver } from './CombatResolver';

/**
 * 战斗准备阶段处理器
 */
class PreparingPhaseHandler implements BattlePhaseHandler {
    phase = BattlePhase.PREPARING;
    priority = 100;

    canHandle(context: BattleContext): boolean {
        return context.state.phase === BattlePhase.PREPARING;
    }

    async handle(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('PreparingPhaseHandler');
        logger.debug(`Processing preparing phase for battle: ${context.state.battleId}`);

        // 验证参与者
        const allParticipants = [...context.state.homeParticipants, ...context.state.awayParticipants];
        if (allParticipants.length === 0) {
            throw new Error('No participants in battle');
        }

        // 验证参与者状态
        for (const participant of allParticipants) {
            if (!participant.component) {
                throw new Error(`Participant ${participant.id} has no component`);
            }
        }

        // 转换到初始化阶段
        const stateManager = new BattleStateManager();
        return stateManager.updatePhase(context, BattlePhase.INITIALIZING);
    }
}

/**
 * 战斗初始化阶段处理器
 */
class InitializingPhaseHandler implements BattlePhaseHandler {
    phase = BattlePhase.INITIALIZING;
    priority = 90;

    canHandle(context: BattleContext): boolean {
        return context.state.phase === BattlePhase.INITIALIZING;
    }

    async handle(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('InitializingPhaseHandler');
        logger.debug(`Processing initializing phase for battle: ${context.state.battleId}`);

        const stateManager = new BattleStateManager();
        let updatedContext = context;

        // 应用光环效果
        updatedContext = await this.applyAuraEffects(updatedContext);

        // 触发战斗开始被动技能
        updatedContext = await this.triggerBattleStartPassives(updatedContext);

        // 初始化临时数据
        updatedContext.temporaryData.set('battle_start_time', Date.now());
        updatedContext.temporaryData.set('auras_applied', true);

        // 转换到回合开始阶段
        return stateManager.updatePhase(updatedContext, BattlePhase.ROUND_START);
    }

    private async applyAuraEffects(context: BattleContext): Promise<BattleContext> {
        // 应用光环效果的逻辑
        // 这里简化处理，实际应该检查所有参与者的光环技能
        const logger = new ServiceLogger('InitializingPhaseHandler');
        logger.debug('Applying aura effects', {
            metadata: { battleId: context.state.battleId }
        });

        // TODO: 实现光环效果应用逻辑
        return context;
    }

    private async triggerBattleStartPassives(context: BattleContext): Promise<BattleContext> {
        // 触发战斗开始时的被动技能
        const logger = new ServiceLogger('InitializingPhaseHandler');
        logger.debug('Triggering battle start passives', {
            metadata: { battleId: context.state.battleId }
        });

        // TODO: 实现战斗开始被动技能触发逻辑
        return context;
    }
}

/**
 * 回合开始阶段处理器
 */
class RoundStartPhaseHandler implements BattlePhaseHandler {
    phase = BattlePhase.ROUND_START;
    priority = 80;

    canHandle(context: BattleContext): boolean {
        return context.state.phase === BattlePhase.ROUND_START;
    }

    async handle(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('RoundStartPhaseHandler');
        const stateManager = new BattleStateManager();
        
        // 推进回合
        let updatedContext = stateManager.advanceRound(context);
        
        logger.info(`Round ${updatedContext.state.currentRound} started`, {
            metadata: { battleId: context.state.battleId }
        });

        // 检查是否达到最大回合数
        if (updatedContext.state.currentRound > updatedContext.state.maxRounds) {
            return stateManager.updatePhase(updatedContext, BattlePhase.BATTLE_END);
        }

        // 检查是否有存活的参与者
        const aliveHome = stateManager.getAliveParticipants(updatedContext, true);
        const aliveAway = stateManager.getAliveParticipants(updatedContext, false);

        if (aliveHome.length === 0 || aliveAway.length === 0) {
            return stateManager.updatePhase(updatedContext, BattlePhase.BATTLE_END);
        }

        // 触发回合开始效果
        updatedContext = await this.triggerRoundStartEffects(updatedContext);

        // 转换到单位行动阶段
        return stateManager.updatePhase(updatedContext, BattlePhase.UNIT_ACTION);
    }

    private async triggerRoundStartEffects(context: BattleContext): Promise<BattleContext> {
        // 触发回合开始效果（如Buff处理、冷却减少等）
        const logger = new ServiceLogger('RoundStartPhaseHandler');
        logger.debug('Triggering round start effects', {
            metadata: { 
                battleId: context.state.battleId,
                round: context.state.currentRound
            }
        });

        // TODO: 实现回合开始效果逻辑
        return context;
    }
}

/**
 * 单位行动阶段处理器
 */
class UnitActionPhaseHandler implements BattlePhaseHandler {
    phase = BattlePhase.UNIT_ACTION;
    priority = 70;

    canHandle(context: BattleContext): boolean {
        return context.state.phase === BattlePhase.UNIT_ACTION;
    }

    async handle(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('UnitActionPhaseHandler');
        const stateManager = new BattleStateManager();
        const combatResolver = new CombatResolver();
        
        let updatedContext = context;

        logger.debug(`Processing unit actions for round ${context.state.currentRound}`, {
            metadata: { battleId: context.state.battleId }
        });

        // 获取存活的参与者
        const aliveHome = stateManager.getAliveParticipants(updatedContext, true);
        const aliveAway = stateManager.getAliveParticipants(updatedContext, false);

        // 主场单位行动
        for (const participant of aliveHome) {
            if (!participant.isAlive) continue;
            
            updatedContext = stateManager.setCurrentActor(updatedContext, participant.id);
            updatedContext = await combatResolver.processUnitAction(updatedContext, participant, aliveAway, aliveHome);
            
            // 检查战斗是否应该结束
            if (stateManager.isBattleOver(updatedContext)) {
                return stateManager.updatePhase(updatedContext, BattlePhase.BATTLE_END);
            }
        }

        // 客场单位行动
        const remainingAway = stateManager.getAliveParticipants(updatedContext, false);
        for (const participant of remainingAway) {
            if (!participant.isAlive) continue;
            
            updatedContext = stateManager.setCurrentActor(updatedContext, participant.id);
            updatedContext = await combatResolver.processUnitAction(updatedContext, participant, aliveHome, remainingAway);
            
            // 检查战斗是否应该结束
            if (stateManager.isBattleOver(updatedContext)) {
                return stateManager.updatePhase(updatedContext, BattlePhase.BATTLE_END);
            }
        }

        // 清除当前行动者
        updatedContext = stateManager.setCurrentActor(updatedContext, undefined);

        // 转换到回合结束阶段
        return stateManager.updatePhase(updatedContext, BattlePhase.ROUND_END);
    }
}

/**
 * 回合结束阶段处理器
 */
class RoundEndPhaseHandler implements BattlePhaseHandler {
    phase = BattlePhase.ROUND_END;
    priority = 60;

    canHandle(context: BattleContext): boolean {
        return context.state.phase === BattlePhase.ROUND_END;
    }

    async handle(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('RoundEndPhaseHandler');
        const stateManager = new BattleStateManager();
        
        logger.debug(`Processing round end for round ${context.state.currentRound}`, {
            metadata: { battleId: context.state.battleId }
        });

        let updatedContext = context;

        // 处理回合结束效果
        updatedContext = await this.processRoundEndEffects(updatedContext);

        // 检查战斗是否结束
        if (stateManager.isBattleOver(updatedContext)) {
            return stateManager.updatePhase(updatedContext, BattlePhase.BATTLE_END);
        }

        // 继续下一回合
        return stateManager.updatePhase(updatedContext, BattlePhase.ROUND_START);
    }

    private async processRoundEndEffects(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('RoundEndPhaseHandler');
        logger.debug('Processing round end effects', {
            metadata: { 
                battleId: context.state.battleId,
                round: context.state.currentRound
            }
        });

        // 处理所有存活单位的回合结束效果
        // 包括：冷却减少、Buff处理、毒伤等
        const stateManager = new BattleStateManager();
        const aliveParticipants = stateManager.getAliveParticipants(context);

        for (const participant of aliveParticipants) {
            // 减少技能冷却
            participant.component.reduceCooldowns();
            
            // 处理Buff效果
            // BuffManager.processBuffs(participant.component);
        }

        return context;
    }
}

/**
 * 战斗结束阶段处理器
 */
class BattleEndPhaseHandler implements BattlePhaseHandler {
    phase = BattlePhase.BATTLE_END;
    priority = 50;

    canHandle(context: BattleContext): boolean {
        return context.state.phase === BattlePhase.BATTLE_END;
    }

    async handle(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('BattleEndPhaseHandler');
        const stateManager = new BattleStateManager();
        
        logger.info(`Battle ending`, {
            metadata: { 
                battleId: context.state.battleId,
                round: context.state.currentRound,
                winner: stateManager.getWinner(context)
            }
        });

        let updatedContext = context;

        // 移除光环效果
        updatedContext = await this.removeAuraEffects(updatedContext);

        // 触发战斗结束效果
        updatedContext = await this.triggerBattleEndEffects(updatedContext);

        // 设置结束时间
        updatedContext = stateManager.updateStatus(updatedContext, BattleStatus.COMPLETED);

        // 转换到完成阶段
        return stateManager.updatePhase(updatedContext, BattlePhase.COMPLETED);
    }

    private async removeAuraEffects(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('BattleEndPhaseHandler');
        logger.debug('Removing aura effects', {
            metadata: { battleId: context.state.battleId }
        });

        // TODO: 实现移除光环效果逻辑
        return context;
    }

    private async triggerBattleEndEffects(context: BattleContext): Promise<BattleContext> {
        const logger = new ServiceLogger('BattleEndPhaseHandler');
        logger.debug('Triggering battle end effects', {
            metadata: { battleId: context.state.battleId }
        });

        // TODO: 实现战斗结束效果逻辑
        return context;
    }
}

/**
 * 战斗阶段管理器
 */
export class BattlePhaseManager {
    private logger: ServiceLogger;
    private handlers: BattlePhaseHandler[];

    constructor() {
        this.logger = new ServiceLogger('BattlePhaseManager');
        
        // 注册所有阶段处理器
        this.handlers = [
            new PreparingPhaseHandler(),
            new InitializingPhaseHandler(),
            new RoundStartPhaseHandler(),
            new UnitActionPhaseHandler(),
            new RoundEndPhaseHandler(),
            new BattleEndPhaseHandler()
        ];

        // 按优先级排序
        this.handlers.sort((a, b) => b.priority - a.priority);
        
        this.logger.info('BattlePhaseManager initialized', {
            metadata: { handlersCount: this.handlers.length }
        });
    }

    /**
     * 处理当前阶段
     */
    async processPhase(context: BattleContext): Promise<BattleContext> {
        const currentPhase = context.state.phase;
        
        this.logger.debug(`Processing phase: ${currentPhase}`, {
            metadata: { 
                battleId: context.state.battleId,
                round: context.state.currentRound,
                status: context.state.status
            }
        });

        // 查找能处理当前阶段的处理器
        const handler = this.handlers.find(h => h.canHandle(context));
        
        if (!handler) {
            const error = new Error(`No handler found for phase: ${currentPhase}`);
            this.logger.error('Phase handler not found', undefined, error);
            throw error;
        }

        try {
            const startTime = Date.now();
            const result = await handler.handle(context);
            const duration = Date.now() - startTime;

            this.logger.debug(`Phase processed successfully: ${currentPhase}`, {
                metadata: { 
                    battleId: context.state.battleId,
                    duration,
                    nextPhase: result.state.phase
                }
            });

            return result;

        } catch (error) {
            this.logger.error(`Phase processing failed: ${currentPhase}`, undefined, error);
            
            // 设置错误状态
            const stateManager = new BattleStateManager();
            const errorContext = stateManager.updateStatus(context, BattleStatus.ERROR);
            
            throw error;
        }
    }

    /**
     * 获取所有注册的处理器
     */
    getHandlers(): BattlePhaseHandler[] {
        return [...this.handlers];
    }

    /**
     * 注册新的阶段处理器
     */
    registerHandler(handler: BattlePhaseHandler): void {
        this.handlers.push(handler);
        this.handlers.sort((a, b) => b.priority - a.priority);
        
        this.logger.info(`Phase handler registered: ${handler.phase}`, {
            metadata: { priority: handler.priority }
        });
    }

    /**
     * 移除阶段处理器
     */
    removeHandler(phase: BattlePhase): boolean {
        const index = this.handlers.findIndex(h => h.phase === phase);
        if (index >= 0) {
            const removed = this.handlers.splice(index, 1)[0];
            this.logger.info(`Phase handler removed: ${removed.phase}`);
            return true;
        }
        return false;
    }

    /**
     * 验证阶段流程的完整性
     */
    validatePhaseFlow(): boolean {
        const requiredPhases = [
            BattlePhase.PREPARING,
            BattlePhase.INITIALIZING,
            BattlePhase.ROUND_START,
            BattlePhase.UNIT_ACTION,
            BattlePhase.ROUND_END,
            BattlePhase.BATTLE_END
        ];

        const missingPhases = requiredPhases.filter(phase => 
            !this.handlers.some(h => h.phase === phase)
        );

        if (missingPhases.length > 0) {
            this.logger.error('Missing phase handlers', {
                metadata: { missingPhases }
            });
            return false;
        }

        this.logger.info('Phase flow validation passed');
        return true;
    }
}
